﻿using System;
using System.Text;
using System.Collections.Generic;
using EnvDTE;
using EnvDTE80;

namespace CoNatural.Data.VisualStudio.AddIn.Helpers {
	internal static class ProjectItemHelper {
		internal static string GetNamespace(ProjectItem item, bool include) {
			List<string> parts = new List<string>();
			if (include)
				parts.Add(item.Name);
			ProjectItem parent = item.Collection.Parent as ProjectItem;
			while (parent != null) {
				parts.Add(parent.Name);
				parent = parent.Collection.Parent as ProjectItem;
			}
			parts.Add(item.ContainingProject.Name);
			parts.Reverse();
			return string.Join(".", parts.ToArray());
		}

		internal static ProjectItems LocateCollection(ProjectItems rootCollection, string rootPath, string rootNamespace, string fullName, out string name, out string _namespace, out string collectionPath) {
			// break full name in parts
			string[] parts = fullName.Split('.');

			// start building namespace
			StringBuilder namespaceSb = new StringBuilder();
			namespaceSb.Append(rootNamespace);

			// traverse/create project folders following namespace
			ProjectItems collection = rootCollection;
			collectionPath = rootPath;
			for (int i = 0; i < parts.Length - 1; i++) {
				string part = parts[i];

				// build namespace
				namespaceSb.Append(".").Append(part);

				// move to or create next folder
				ProjectItem folder = null;
				try {
					folder = collection.Item(part);
					if (folder.Properties.Count > 10)
						folder = null; // this is an item
				}
				catch { }
				if (folder == null)
					folder = collection.AddFolder(part, null);
				collection = folder.ProjectItems;

				// update collection path
				collectionPath = folder.Properties.Item("FullPath").Value.ToString();
			}

			name = parts[parts.Length - 1];
			_namespace = namespaceSb.ToString();
			return collection;
		}
	}
}
